package com.lichuandi.controller;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
 * @author admin
 */
@RestController
public class CropController {

    @PostMapping(value = "/api/crop", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> cropImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("cropData") String cropData){

        try {
            // 解析裁剪参数
            Map<String, Integer> params = parseCropData(cropData);

            // 转换并验证参数
            int x = params.getOrDefault("x", 0);
            int y = params.getOrDefault("y", 0);
            int width = params.getOrDefault("width", 0);
            int height = params.getOrDefault("height", 0);

            // 读取图片
            BufferedImage originalImage = ImageIO.read(file.getInputStream());

            // 验证裁剪区域
            validateCropArea(originalImage, x, y, width, height);

            // 参数述
            BufferedImage croppedImage = originalImage.getSubimage(x, y, width, height);

            // 转换结果到字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(croppedImage, "png", baos);

            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_PNG)
                    .body(baos.toByteArray());

        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(("处理失败: " + e.getMessage()).getBytes());
        }
    }



    private Map<String, Integer> parseCropData(String cropData) {
        return Pattern.compile("&")
                .splitAsStream(cropData)
                .map(s -> s.split("="))
                .collect(Collectors.toMap(
                        arr -> arr[0],
                        arr -> Integer.parseInt(arr[1]))
                );
    }

    private void validateCropArea(BufferedImage image, int x, int y, int w, int h) {
        if (x < 0 || y < 0 || w <= 0 || h <= 0) {
            throw new IllegalArgumentException("无效的裁剪参数");
        }
        if (x + w > image.getWidth() || y + h > image.getHeight()) {
            throw new IllegalArgumentException("裁剪区域超出图片范围");
        }
    }
}
